<template>
  <div class="email-message-container">
    <!-- 顶部标题栏 -->
    <div class="email-header">
      <h2><el-icon><Message /></el-icon> 我的消息</h2>
      <div class="header-actions">
        <el-button type="primary" plain @click="refreshMessages">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button type="info" plain @click="markAllAsRead" :disabled="messages.length === 0">
          <el-icon><Reading /></el-icon> 全部已读
        </el-button>
      </div>
    </div>

    <!-- 消息主体区域 -->
    <div class="email-content">
      <!-- 左侧消息列表 -->
      <div class="message-list">
        <el-input
            v-model="searchQuery"
            placeholder="搜索消息"
            clearable
            :prefix-icon="Search"
            class="search-input"
        />

        <div class="message-scroll-container">
          <div
              v-for="msg in filteredMessages"
              :key="msg.id"
              class="message-item"
              :class="{
              'unread': !msg.read,
              'selected': selectedMessage?.id === msg.id
            }"
              @click="selectMessage(msg)"
          >
            <div class="message-header">
              <span class="sender">{{ msg.sender }}</span>
              <span class="time">{{ formatTime(msg.time) }}</span>
            </div>
            <div class="message-title">
              <el-icon v-if="msg.important" color="#F56C6C"><StarFilled /></el-icon>
              {{ msg.title }}
            </div>
            <div class="message-preview">{{ msg.preview }}</div>
            <div v-if="msg.attachments" class="message-attachments">
              <el-icon><Paperclip /></el-icon>
              {{ msg.attachments.length }}个附件
            </div>
          </div>

          <el-empty v-if="filteredMessages.length === 0" description="暂无消息" />
        </div>
      </div>

      <!-- 右侧消息详情 -->
      <div class="message-detail" v-if="selectedMessage">
        <div class="detail-header">
          <h3>{{ selectedMessage.title }}</h3>
          <div class="detail-actions">
            <el-button type="text" @click="replyMessage">
              <el-icon><Position /></el-icon> 回复
            </el-button>
            <el-button type="text" @click="forwardMessage">
              <el-icon><Share /></el-icon> 转发
            </el-button>
            <el-button type="text" @click="deleteMessage">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </div>
        </div>

        <div class="detail-meta">
          <div class="meta-item">
            <span class="meta-label">发件人:</span>
            <span class="meta-value">{{ selectedMessage.sender }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">收件人:</span>
            <span class="meta-value">{{ selectedMessage.receiver }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">时间:</span>
            <span class="meta-value">{{ formatFullTime(selectedMessage.time) }}</span>
          </div>
        </div>

        <el-divider />

        <div class="detail-body">
          <div v-html="selectedMessage.content"></div>
        </div>

        <div v-if="selectedMessage.attachments" class="detail-attachments">
          <h4>附件 ({{ selectedMessage.attachments.length }})</h4>
          <div class="attachment-list">
            <div
                v-for="(file, index) in selectedMessage.attachments"
                :key="index"
                class="attachment-item"
            >
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ file.name }}</span>
              <span class="file-size">({{ formatFileSize(file.size) }})</span>
              <el-button type="text" @click="downloadAttachment(file)">
                <el-icon><Download /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-detail">
        <el-empty description="请选择一条消息查看详情" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  Message,
  Refresh,
  Reading,
  Search,
  StarFilled,
  Paperclip,
  Position,
  Share,
  Delete,
  Document,
  Download
} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

// 模拟消息数据
const messages = ref([
  {
    id: 1,
    title: '预约成功通知',
    sender: '医院预约系统',
    receiver: '我的邮箱',
    time: new Date('2023-05-20 10:30'),
    content: '<p>尊敬的用户：</p><p>您已成功预约张医生5月25日上午10:00的门诊，请提前15分钟到达医院。</p>',
    preview: '您已成功预约张医生5月25日上午10:00的门诊...',
    read: false,
    important: true,
    attachments: [
      {name: '预约确认单.pdf', size: 245678}
    ]
  },
  {
    id: 2,
    title: '检查报告已生成',
    sender: '检验科',
    receiver: '我的邮箱',
    time: new Date('2023-05-18 14:15'),
    content: '<p>您的血液检查报告已生成，请登录系统查看详情。</p>',
    preview: '您的血液检查报告已生成，请登录系统查看...',
    read: true,
    important: false,
    attachments: [
      {name: '血液检查报告.pdf', size: 356789},
      {name: '检查说明.docx', size: 12345}
    ]
  }
])

const searchQuery = ref('')
const selectedMessage = ref(null)

// 过滤后的消息列表
const filteredMessages = computed(() => {
  if (!searchQuery.value) return messages.value
  return messages.value.filter(msg =>
      msg.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      msg.sender.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      msg.content.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 选择消息
const selectMessage = (msg) => {
  selectedMessage.value = msg
  // 标记为已读
  if (!msg.read) {
    msg.read = true
  }
}

// 刷新消息
const refreshMessages = () => {
  ElMessage.success('消息已刷新')
}

// 标记全部已读
const markAllAsRead = () => {
  messages.value.forEach(msg => msg.read = true)
  ElMessage.success('全部标记为已读')
}

// 回复消息
const replyMessage = () => {
  ElMessage.info('回复消息功能')
}

// 转发消息
const forwardMessage = () => {
  ElMessage.info('转发消息功能')
}

// 删除消息
const deleteMessage = () => {
  if (selectedMessage.value) {
    messages.value = messages.value.filter(msg => msg.id !== selectedMessage.value.id)
    selectedMessage.value = null
    ElMessage.success('消息已删除')
  }
}

// 下载附件
const downloadAttachment = (file) => {
  ElMessage.info(`开始下载: ${file.name}`)
  // 实际项目中这里应该是文件下载逻辑
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleDateString()
}

const formatFullTime = (date) => {
  return date.toLocaleString()
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 初始化选中第一条未读消息
onMounted(() => {
  const firstUnread = messages.value.find(msg => !msg.read)
  if (firstUnread) {
    selectMessage(firstUnread)
  } else if (messages.value.length > 0) {
    selectMessage(messages.value[0])
  }
})
</script>

<style scoped>
.email-message-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.email-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
}

.email-content {
  display: flex;
  flex: 1;
  height: calc(100% - 65px);
}

.message-list {
  width: 320px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.search-input {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

.message-scroll-container {
  flex: 1;
  overflow-y: auto;
}

.message-item {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item.selected {
  background-color: #ecf5ff;
}

.message-item.unread {
  background-color: #f8f9fe;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
}

.sender {
  font-weight: bold;
  color: #333;
}

.time {
  color: #999;
}

.message-title {
  font-weight: bold;
  margin-bottom: 6px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.message-preview {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6px;
}

.message-attachments {
  font-size: 12px;
  color: #888;
  display: flex;
  align-items: center;
  gap: 4px;
}

.message-detail {
  flex: 1;
  padding: 24px;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.empty-detail {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
}

.detail-meta {
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.meta-label {
  color: #666;
  width: 60px;
}

.meta-value {
  color: #333;
}

.detail-body {
  line-height: 1.6;
  margin-bottom: 24px;
}

.detail-attachments {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px dashed #ddd;
}

.attachment-list {
  margin-top: 12px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  gap: 8px;
}

.file-name {
  flex: 1;
}

.file-size {
  color: #999;
  font-size: 12px;
}
</style>
